package cn.com.headfree.file.controller;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.nacos.client.utils.StringUtils;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.TCommonFile;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.file.service.IFileService;
import cn.com.headfree.vo.DealFileContion;
import cn.com.headfree.vo.FileNode;
import cn.com.headfree.vo.file.DealFileVo;


/**
 * 附件处理controller
 *
 * @author xuliang
 */
@Controller
@RequestMapping(value = "/fileDeal", produces = "application/json;charset=UTF-8")
public class FileController extends ExBaseController {
    private static final Logger LOG = LogManager.getLogger(FileController.class);
    @Autowired
    public IFileService fileService;
  //基本信息
    @Value("${t_emp_base_info}")
    private String t_emp_base_info;
    
   /**
       *   文件上传、编辑接口
    * @param request
    * @param orignalId 原业务id
    * @param isAdd  是否新增接口（0-》新增  1-》编辑  2->审核）
    * @param businessId （业务id）
    * @param businessTypeId （业务类型id）
    * @param fileId （文件id）
    * @param fileName （文件名）
    * @param isPass （审核是否通过:0->通过  1->不通过）
    * @return
    */
    @RequestMapping("/dealFile")
    @ResponseBody
	public ResultData dealFile( HttpServletRequest request,@RequestBody DealFileContion dealFileContion) {
		ResultData result = new ResultData();
		try{
			User user = this.getLoginUserInfo(request);
			List<DealFileVo> files=new ArrayList<DealFileVo>();
			List<FileNode> fileNodes=dealFileContion.getFileNodes();
			String businessId=dealFileContion.getBusinessId();
			String businessTypeId=dealFileContion.getBusinessTypeId();
			String isAdd=dealFileContion.getIsAdd();
			String orignalId=dealFileContion.getOrignalId();
			if(user!=null) {
				if(fileNodes!=null) {
					if(fileNodes.size()>0) {
						for(int i=0;i<fileNodes.size();i++) {
							DealFileVo f=new DealFileVo();
							f.setFileId(fileNodes.get(i).getFileId());
							f.setFileName(fileNodes.get(i).getFileName());
							f.setBusinessNode(fileNodes.get(i).getBusinessNode());
							f.setCreaterId(user.getFax());
							f.setCreaterName(user.getName());
							f.setUpdaterId(user.getFax());
							f.setUpdaterName(user.getName());
							f.setBusinessId(businessId);
							f.setBusinessTypeId(businessTypeId);
							f.setOrderNum(i);
							files.add(f);
						}
					}
				}
				//如果是新增
				if("0".equals(isAdd)) {
					if(files!=null&&files.size()>0) {
						try {
							fileService.addFile(files);
							LOG.info("文件信息入库成功！");
							result.setData("文件信息入库成功！");
						} catch (Exception e) {
							result.setSuccess(false);
							result.setErrorMsg("文件信息入库失败！");
							e.printStackTrace();
						}
					}else {
						LOG.info("未选择文件进行上传");
					}
				}else if("1".equals(isAdd)){
					//如果是编辑
					if(t_emp_base_info.equals(businessTypeId)) {
						fileService.deleteFileByBusinessId(businessId);
						if(files!=null&&files.size()>0) {
							try {
								for(DealFileVo f:files) {
									f.setBusinessId(orignalId);
								}
								fileService.addFile(files);
								LOG.info("文件信息入库成功！");
								result.setData("文件信息入库成功！");
							} catch (Exception e) {
								result.setSuccess(false);
								result.setErrorMsg("文件信息入库失败！");
								e.printStackTrace();
							}
						}else {
							LOG.info("未选择文件进行上传");
						}
					}else {
						//如果登陆人是普通用户
						if("1".equals(user.getRemark())) {
							if(files!=null&&files.size()>0) {
								try {
									fileService.addFile(files);
									LOG.info("文件信息入库成功！");
									result.setData("文件信息入库成功！");
								} catch (Exception e) {
									result.setSuccess(false);
									result.setErrorMsg("文件信息入库失败！");
									e.printStackTrace();
								}
							}else {
								LOG.info("未选择文件进行上传");
							}
						}else {
							//如果登陆人是管理员（管理员不需要审核，直接形成有效数据），先删除，再添加
							fileService.deleteFileByBusinessId(orignalId);
							if(files!=null&&files.size()>0) {
								try {
									for(DealFileVo f:files) {
										f.setBusinessId(orignalId);
									}
									fileService.addFile(files);
									LOG.info("文件信息入库成功！");
									result.setData("文件信息入库成功！");
								} catch (Exception e) {
									result.setSuccess(false);
									result.setErrorMsg("文件信息入库失败！");
									e.printStackTrace();
								}
							}else {
								LOG.info("未选择文件进行上传");
							}
						}
					}
				}else if("2".equals(isAdd)) {
					String isPass=dealFileContion.getIsPass();
					//如果是审核
					//（审核通过，直接形成有效数据），先删除，再添加
					if(isPass!=null&&("0".equals(isPass))) {
						fileService.deleteFileByBusinessId(orignalId);
						if(files!=null&&files.size()>0) {
							try {
								for(DealFileVo f:files) {
									f.setBusinessId(orignalId);
								}
								fileService.addFile(files);
								LOG.info("文件信息入库成功！");
								result.setData("文件信息入库成功！");
							} catch (Exception e) {
								result.setSuccess(false);
								result.setErrorMsg("文件信息入库失败！");
								e.printStackTrace();
							}
						}else {
							LOG.info("未选择文件进行上传");
						}
					}
				}else if("3".equals(isAdd)) {//如果是对于有多个参与人的类型(如学术成果等)在新增时根据名称进行下拉选择回显编辑的
					String flowStatus = dealFileContion.getFlowStatus();
					//如果是对有效数据进行回显编辑，那么就走正常编辑流程，管理员编辑时不用对附件进行处理了，因为是update原来那条数据，且附件不允许编辑
					//如果是对待审核数据进行回显编辑，不管是管理员还是普通人员都不用对附件进行处理，因为也是update原来那条数据，且附件不允许编辑
					//如果是对被驳回数据进行回显编辑，不管是管理员还是普通人员都是add一条新的数据，所以要对原来的附件进行重新插入一次
					if(flowStatus!=null && ("1".equals(flowStatus))) {//有效数据
						if("1".equals(user.getRemark())) {//普通人员编辑
							if(files!=null&&files.size()>0) {
								try {
									fileService.addFile(files);
									LOG.info("文件信息入库成功！");
									result.setData("文件信息入库成功！");
								} catch (Exception e) {
									result.setSuccess(false);
									result.setErrorMsg("文件信息入库失败！");
									e.printStackTrace();
								}
							}else {
								LOG.info("未选择文件进行上传");
							}
						}
					}else if(flowStatus!=null && ("3".equals(flowStatus))){//被驳回数据
						if(files!=null&&files.size()>0) {
							try {
								fileService.addFile(files);
								LOG.info("文件信息入库成功！");
								result.setData("文件信息入库成功！");
							} catch (Exception e) {
								result.setSuccess(false);
								result.setErrorMsg("文件信息入库失败！");
								e.printStackTrace();
							}
						}else {
							LOG.info("未选择文件进行上传");
						}
					}
				}
			}else {
				result.setSuccess(false);
				result.setErrorMsg("当前登录用户获取失败！");
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}
    
    
    /**
         *  根据业务id获取对应附件集合
     * @param request
     * @param businessId
     * @return
     */
    @RequestMapping("/getFilesByBusinessId")
    @ResponseBody
    public ResultData getFilesByBusinessId( HttpServletRequest request,String businessId) {
        ResultData result = new ResultData();
//        User user = this.getLoginUserInfo(request);
        try {
        	result=fileService.getFilesByBusinessId(businessId);
            LOG.info("查询附件列表成功！");
        } catch (Exception e) {
            result.setErrorMsg("查询附件列表异常");
            result.setSuccess(false);
            LOG.error("查询附件列表异常", e);
        }
        return result;
    }
    
    
    @RequestMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	@ResponseBody
	public ResultData upload(@RequestPart("file") MultipartFile file, TCommonFile commonFile) {
		ResultData result =new ResultData();
//		try {
//			result = fileService.upload(file,commonFile);
//			LOG.info("human-manage-ding调用human-manage的upload成功");
//		} catch(Exception e) {
//			result.setSuccess(false);
//			result.setErrorMsg("human-manage-ding调用human-manage的upload出现异常");
//			LOG.error("human-manage-ding调用human-manage的upload出现异常", e);
//		}
		
		
		try {
			List<MultipartFile> files = new ArrayList<MultipartFile>();
			files.add(file);
			result = fileService.upload(files, commonFile);
		} catch (Exception e) {
			LOG.error("上传文件出错",e.getMessage());
		}
		return result;
	}
    
    
    @RequestMapping(value = "/download")
   	public void download(HttpServletResponse response,String fileId) throws Exception {
//   		ResultData result =new ResultData();
//   		try {
//   			fileService.download(fileId);
//   			LOG.info("human-manage-ding调用human-manage的download成功");
//   		} catch(Exception e) {
//   			result.setSuccess(false);
//   			result.setErrorMsg("human-manage-ding调用human-manage的download出现异常");
//   			LOG.error("human-manage-ding调用human-manage的download出现异常", e);
//   		}
    	if(StringUtils.isNotBlank(fileId)) {
			try {
				fileService.getSingleFile(response, fileId);
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error("下载文件出错",e.getMessage());
			}
		}else {
			LOG.error("参数fileId不可为空");
			throw new Exception("参数fileId不可为空");
		}
   	}

    
    @RequestMapping(value = "/findFileList")
   	@ResponseBody
   	public ResultData findFileList(@RequestParam(required = true) String sysCode, @RequestParam(required = true) String businessId, String businessNode) {
   		ResultData result =new ResultData();
   		try {
   			result = fileService.findFileList(sysCode,businessId,businessNode);
   			LOG.info("human-manage-ding调用human-manage的findFileList成功");
   		} catch(Exception e) {
   			result.setSuccess(false);
   			result.setErrorMsg("human-manage-ding调用human-manage的findFileList出现异常");
   			LOG.error("human-manage-ding调用human-manage的findFileList出现异常", e);
   		}
   		return result;
   	}
    
    
    @RequestMapping("/deleteFile")
    @ResponseBody
	public ResultData deleteFile(@RequestParam(required = true) String fileId) {
    	ResultData result =new ResultData();
   		try {
   			result = fileService.deleteFile(fileId);
   			LOG.info("human-manage-ding调用human-manage的deleteFile成功");
   		} catch(Exception e) {
   			result.setSuccess(false);
   			result.setErrorMsg("human-manage-ding调用human-manage的deleteFile出现异常");
   			LOG.error("human-manage-ding调用human-manage的deleteFile出现异常", e);
   		}
   		return result;
	}
}
